#include "headfiles.h"

using namespace std;

void *alignedMalloc(size_t size, size_t alignment) {
    if ((alignment & (alignment - 1)) != 0) {
        cout << "Incorrect alignment number" << endl;
        return NULL;
    }

    char *ptr = (char *)malloc(size + alignment + sizeof(size_t));
    if (ptr == NULL) {
        cout << "Allocate buffer error, NULL!" << endl;
        return NULL;
    }

    char *tmp = ptr + sizeof(size_t);
    unsigned long long addr_val = (((unsigned long long)tmp + alignment - 1) / alignment) * alignment;
    char *ret_addr = (char *)addr_val;
    size_t offset_val = ret_addr - tmp;
    size_t *offset_ptr = (size_t *)(ret_addr - 4);
    *offset_ptr = offset_val;

    return (void *)ret_addr;
}

void alignedFree(void *ptr) {
    size_t *offset_ptr = (size_t *)((char *)ptr - 4);
    size_t offset = *offset_ptr;
    char *orig_ptr = (char *)ptr - 4 - offset;
    free(orig_ptr);

    return;
}
